package com.hsf.cloudweb.controller;

import com.hsf.cloudweb.controller.form.UserForm;
import com.hsf.cloudweb.enums.ResponseEnum;
import com.hsf.cloudweb.model.MySqlUserInfo;
import com.hsf.cloudweb.model.ServiceResponse;
import com.hsf.cloudweb.model.UserInfo;
import com.hsf.cloudweb.service.FeignService;
import com.hsf.cloudweb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private FeignService feignService;

    @Value("${rpcServices.serviceName}")
    private String serviceName;

    @Value("${rpcServices.contextPath}")
    private String contextPath;

    @Value("${rpcServices.indexUrl}")
    private String indexUrl;

    @Value("${rpcServices.userInfoUrl}")
    private String userInfoUrl;


    @RequestMapping(path="/saveUser",method= RequestMethod.POST)
    public UserInfo saveUser(@RequestBody UserInfo userInfo){
        logger.info("/saveUser request parameters:{}",userInfo.toString());
        return userService.saveUser(userInfo);
    }

    @RequestMapping(path = "/findUser",method=RequestMethod.GET)
    public UserInfo findUserbyUserAccount(@RequestParam("userAccount") String userAccount){
        logger.info("/findUser request param:{}",userAccount);
        return userService.findUserByUserAccount(userAccount);
    }

    @RequestMapping(path="/login",method= RequestMethod.POST)
    public ServiceResponse<String> userLogin(@RequestParam("userAccount") String userAccount, @RequestParam("password") String password,
                                             HttpServletRequest request){
        UserForm form = new UserForm();
        form.setUserAccount(userAccount);
        form.setPassword(password);
        logger.info("/login request params:{}",form);
        ServiceResponse<String> response = null;
        if(StringUtils.isEmpty(form.getUserAccount())){
            response = new ServiceResponse<>(ResponseEnum.PARAM_ERROR.getStatus(),"userAccount cannot be null");
            return response;
        }
        if(StringUtils.isEmpty(form.getPassword())){
            response = new ServiceResponse<>(ResponseEnum.PARAM_ERROR.getStatus(),"password cannot be null");
            return response;
        }
        HttpSession session = request.getSession();

        //在此之前未登录
        if(null==session.getAttribute("userAccount")){
            boolean  result = userService.login(form.getUserAccount(),form.getPassword());
            if(result){
                session.setAttribute("userAccount",form);
//                session.setMaxInactiveInterval(30);
                response = new ServiceResponse<>(ResponseEnum.SUCCESS.getStatus(),ResponseEnum.SUCCESS.getMsg());
                response.setData("login success");
            }else{
                response = new ServiceResponse<>(ResponseEnum.LOGIN_ERROR.getStatus(),ResponseEnum.LOGIN_ERROR.getMsg());
                response.setData("login failed");
            }
        }else{
            response = new ServiceResponse<>(ResponseEnum.SUCCESS.getStatus(),ResponseEnum.SUCCESS.getMsg());
            response.setData("You already have login success!");
        }
        return response;
    }

    @RequestMapping(path="/logout/{userAccount}",method = RequestMethod.GET)
    public ServiceResponse<String> logout(@PathVariable String userAccount, HttpServletRequest request){
        logger.info("/logout request param:{}",userAccount);
        ServiceResponse<String> response = null;
        if(StringUtils.isEmpty(userAccount)){
            response = new ServiceResponse<>(ResponseEnum.PARAM_ERROR.getStatus(),"userAccount cannot be null");
            return response;
        }
        HttpSession session = request.getSession();
        //删除session中的用户信息
        session.removeAttribute("userAccount");
        response = new ServiceResponse<>(ResponseEnum.SUCCESS.getStatus(),"login out success");
        return response;
    }

    @RequestMapping(path="/modify/pass",method = RequestMethod.POST)
    public ServiceResponse<String> modifyPassword(@RequestBody UserForm form){
        logger.info("/modify/pass request params:{}",form);
        ServiceResponse<String> response = null;
        if(StringUtils.isEmpty(form.getUserAccount())){
            response = new ServiceResponse<>(ResponseEnum.PARAM_ERROR.getStatus(),"userAccount cannot be null");
            return response;
        }
        if(StringUtils.isEmpty(form.getPassword())){
            response = new ServiceResponse<>(ResponseEnum.PARAM_ERROR.getStatus(),"password cannot be null");
            return response;
        }
        userService.modifyPassword(form.getUserAccount(),form.getPassword());
        response = new ServiceResponse<>(ResponseEnum.SUCCESS.getStatus(),ResponseEnum.SUCCESS.getMsg());
        response.setData("modify password success");
        return response;
    }

    @RequestMapping(path="/localIndex",method = RequestMethod.GET)
    public String index(){
        logger.info("/localIndex request start");
        StringBuilder builder = new StringBuilder("http://");
        builder.append(serviceName).append(contextPath).append(indexUrl);
        String uri = builder.toString();
        logger.info("uri:"+uri);
        ResponseEntity<String> entity = restTemplate.getForEntity(uri,String.class);
        return entity.getBody();
    }

    @RequestMapping(path="/remoteUserInfo",method = RequestMethod.GET)
    public ResponseEntity<MySqlUserInfo> queryMysqlUserInfo(@RequestParam("userAccount") String userAccount) {
        logger.info("/remoteUserInfo request start");
        logger.info("userAccount:"+userAccount);
        StringBuilder builder = new StringBuilder("http://");
        builder.append(serviceName).append(contextPath).append(userInfoUrl).append("?userAccount={userAccount}");
        String uri = builder.toString();
        logger.info("uri:"+uri);
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("userAccount",userAccount);
        ResponseEntity<MySqlUserInfo> entity =  restTemplate.getForEntity(uri,MySqlUserInfo.class,paramMap);
        return entity;
    }

    @GetMapping(value="/remoteUrl")
    public String getRemoteUri(){
        return feignService.getUrl();
    }

    @GetMapping(value="/feignUserInfo")
    public MySqlUserInfo getRemoteUserInfo(String userAccount){

        return  feignService.getUserInfo(userAccount);
    }




}
